package com.jgdt.codegen;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
//import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
 * @description: 自动生成 mvc开发层
 * @author: huangAn
 * @createDate: 2025/04/18
 */
public class CodeGenerator {

    private static final String url = "jdbc:mysql://127.0.0.1:3306/kas";
    private static final String driver = "com.mysql.cj.jdbc.Driver";
    private static final String user = "root";
    private static final String password = "root";
    /**是否启用swagger*/
    private static final boolean enableSwagger = false;
    /**包名*/
    private static final String packagePath = "com.qem";
    /**模块名*/
    private static final String moduleName = null;
    /**是否启用Lombok*/
    private static final boolean enableLombok = true;
    /**生成文件位置*/
    private static final String basePath = "\\mall-kas-biz";
    /**忽略表前缀,忽略多个使用 ','分割*/
    private static final String tablePreFix = "QEM_";
    /**是否生成controller*/
    private static final boolean enableController = true;

    private static final String superEntity = "";
    private static final String superEntityColumns = "id,version,deleted,create_time,create_user_id,update_time,update_user_id";
    private static final String superController = "";
    private static final String superService = "cn.com.crc.ripplescloud.common.base.service.RipplesBaseService";
    private static final String superServiceImpl = "cn.com.crc.ripplescloud.common.base.service.impl.RipplesBaseServiceImpl";
    private static final String superMapper = "cn.com.crc.ripplescloud.common.base.mapper.RipplesBaseMapper";


    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
//        String projectPath = System.getProperty("user.dir");
        String projectPath = "D:\\project\\mall_kas" + basePath;
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("chenzg");
        gc.setOpen(false);
        //实体属性 Swagger2 注解
//         gc.setSwagger2(enableSwagger);
        mpg.setGlobalConfig(gc);
        //设置生成的service接口的名字的首字母是否为I
        gc.setServiceName("%sService");
        //时间类型对应策略
//        gc.setDateType(DateType.ONLY_DATE);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(url);
        // dsc.setSchemaName("public");
        dsc.setDriverName(driver);
        dsc.setUsername(user);
        dsc.setPassword(password);
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
//        if(StringUtils.isNotEmpty(moduleName)) {
//            pc.setModuleName(moduleName);
//        } else {
//            pc.setModuleName(scanner("模块名称"));
//        }

        //包名自定义
        String classifyName = scanner("模块名称");
        pc.setEntity("entity".concat(".").concat(classifyName));
        pc.setMapper("mapper".concat(".").concat(classifyName));
        pc.setService("service".concat(".").concat(classifyName));
        pc.setServiceImpl("service".concat(".").concat(classifyName).concat(".").concat("impl"));
        pc.setController("controller".concat(".").concat(classifyName));

        pc.setParent(packagePath);
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        //不生成controller
        if(enableController) {
           templateConfig.setController("");
        }


        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        if(StringUtils.isNotBlank(superEntity)) {
            strategy.setSuperEntityClass(superEntity);
        }


        strategy.setEntityLombokModel(enableLombok);
        strategy.setRestControllerStyle(enableController);
        // 公共父类
        if(StringUtils.isNotBlank(superController)) {
            strategy.setSuperControllerClass(superController);
        }
        if(StringUtils.isNotBlank(superService)) {
            strategy.setSuperServiceClass(superService);
        }

        if(StringUtils.isNotBlank(superServiceImpl)) {
            strategy.setSuperServiceImplClass(superServiceImpl);
        }


        if(StringUtils.isNotBlank(superMapper)) {
            strategy.setSuperMapperClass(superMapper);
        }

        // 写于父类中的公共字段
//        if(StringUtils.isNotBlank(superEntityColumns)) {
//            strategy.setSuperEntityColumns(superEntityColumns.split(","));
//        }

        //生成表取消前缀
        if(StringUtils.isNotBlank(tablePreFix)) {
            strategy.setTablePrefix(tablePreFix.split(","));
        }



        strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
//        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}